package com.demo.zyt.common.utils;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WeChatAesUtils {
  public static String decryptWXAppletInfo(String sessionKey, String encryptedData, String iv)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
      InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    String result = null;
    byte[] encrypData = Base64.decodeBase64(encryptedData);
    byte[] ivData = Base64.decodeBase64(iv);
    byte[] sessionKeyB = Base64.decodeBase64(sessionKey);

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec keySpec = new SecretKeySpec(sessionKeyB, "AES");
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    byte[] doFinal = cipher.doFinal(encrypData);
    result = new String(doFinal);
    return result;
  }
  
  public static void main(String[] args) throws Exception{
	  String sessionKey = "FQT\\/K5KxsPDwAyxGPlCCEg==";
	  String encryptedData = "71XYDhIxwj8V4Uztnh+RKuBTr0Mw8/WLsiFwaxAQbn8ADOF4YUSalS1ePW806HWJ+SXLRC6364lb1oL4rZr4Ga083JYJfR3WneedH49jDuo11pL1ObLJdPSvUZHrng+raEzHLHTjAyVgf/Ixb4ywIZ1BeKF2B9xpAg4cl0GaAhfbU1h0UYq92UJStlA0LZpoRya3DBLAz5Om4CIRH1T2KQ==";
	  String iv = "lbK2vjmI604eLQqgsumjYA==";
	  String result = WeChatAesUtils.decryptWXAppletInfo(sessionKey, encryptedData, iv);
	  log.info(result);
	  
	  encryptedData = "iCnq6MuMwxkj9JZ+1MvCiyv+ZvShVWuSxJJWN2fzUSbuN2FyeEc6qfVrfEZqfpnEb8MwklUvvZ3xAwcBkuZ9tUuY0XxUkW7GQgqmJlQ4rUIjBtDDnuBtz7ynqJUEsK56OfAHh+f6BQ8kmM1LT4meJ5jQH+0ALKaGlW4k/VmVkwO3Scp0kz62W8XiFT8TpCwfURgQTAuxR1mY+TvJRo6yilZpBdZaYsmvyg5EHwC2FPNkQtLhr44oQr5g8pHZ9F58kjyiolCe2B8wab24hgS4lIZPuAcWqGFn5sL49KCJHKgw0eVEjVrf6nQ7g4dWcIPv5dmCDSSqK24uFlbFjZObeunc1XBFyx/G3b/mQxXMHtETFLNg2IRFf3jBg6fNGsyXM0FldABDMR1AxSeIbgDZrGy2PwZjsyIRRZ70Z2ewag238pU0Z1bzNqxANXPdqhKpLxxLK5HTLrP3O/88c0hufYW2b/35s8W0aPwhIlH8Ex4=";
	  iv = "uk4mVtdEQc3GaHQLBz+YmA==";
	  result = WeChatAesUtils.decryptWXAppletInfo(sessionKey, encryptedData, iv);
	  log.info(result);
  }
}
